package com.ruoyi.quality.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ruoyi.baseData.domain.Team;
import com.ruoyi.common.core.exception.GlobalException;
import com.ruoyi.common.core.utils.bean.BeanUtils;
import com.ruoyi.common.core.utils.sql.QueryHelp;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.quality.domain.InspectionIqc;
import com.ruoyi.quality.domain.InspectionItem;
import com.ruoyi.quality.domain.InspectionTask;
import com.ruoyi.quality.domain.InspectionTaskTemplateSamplingItem;
import com.ruoyi.quality.domain.dto.InspectionIqcDto;
import com.ruoyi.quality.domain.dto.InspectionItemDto;
import com.ruoyi.quality.domain.dto.InspectionTaskDto;
import com.ruoyi.quality.domain.vo.InspectionIqcVo;
import com.ruoyi.quality.mapper.InspectionIqcMapper;
import com.ruoyi.quality.service.InspectionIqcService;
import com.ruoyi.quality.service.InspectionTaskService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 *
 */
@Service
public class InspectionIqcServiceImpl implements InspectionIqcService{
    @Resource
    InspectionIqcMapper inspectionIqcMapper;

    @Resource
    InspectionTaskService inspectionTaskService;

    @Override
    public Page<InspectionIqcVo> getInspectionIqcByPage(InspectionIqcDto pageEntity) {
        MPJLambdaWrapper<InspectionIqc> wrapper = new MPJLambdaWrapper<InspectionIqc>()
                .selectAll(InspectionIqc.class)//查询user表全部字段
                //记的测试阶段
                .eq(InspectionIqc::getDelFlag, 0)
                .orderByDesc(InspectionIqc::getCreateTime);
        wrapper = QueryHelp.getPredicateEx(wrapper, InspectionIqc.class, pageEntity);
        Page<InspectionIqcVo> userList = inspectionIqcMapper.selectJoinPage(new Page<>(pageEntity.getCurrentPage(), pageEntity.getPageSize()),   InspectionIqcVo.class, wrapper);
        return userList;
    }

    @Override
    public void addInspectionIqc(InspectionIqcDto testDto) throws ParseException {
        String userName = SecurityUtils.getUsername();
        MPJLambdaWrapper<InspectionIqc> wrapper = new MPJLambdaWrapper<InspectionIqc>()
                .eq(InspectionIqc::getCode, testDto.getCode())
                .ne(InspectionIqc::getDelFlag, 1);
        InspectionIqc material = inspectionIqcMapper.selectOne(wrapper);
        if(null != material) {
            throw new GlobalException("该抽样方案已经存在");
        }
        InspectionIqc test2 = new InspectionIqc();
        BeanUtils.copyProperties(testDto, test2, new String[]{"id"});
        test2.setDelFlag(false);
        test2.setCreateBy(userName);
        test2.setCreateTime(new Date());
        inspectionIqcMapper.insert(test2);
    }

    @Override
    public void updateInspectionIqc(InspectionIqcDto testDto) {
        String userName = SecurityUtils.getUsername();
        MPJLambdaWrapper<InspectionIqc> wrapper = new MPJLambdaWrapper<InspectionIqc>()
                ;
        InspectionIqc inspectionIqc = inspectionIqcMapper.selectOne(wrapper);
        if(null == inspectionIqc) {
            throw new GlobalException("该InspectionIqc不存在");
        }
        BeanUtils.copyProperties(testDto, inspectionIqc);
        inspectionIqc.setUpdateBy(userName);
        inspectionIqc.setUpdateTime(new Date());
        inspectionIqcMapper.updateById(inspectionIqc);
    }

    @Override
    public void delInspectionIqc(InspectionIqcDto testDto) {
        InspectionIqc material = inspectionIqcMapper.selectById(testDto.getId());
        if(null == material) {
            throw new GlobalException("该InspectionIqc不存在");
        }
        material.setDelFlag(true);
        inspectionIqcMapper.updateById(material);
    }

    @Override
    public String uploadInspectionIqc(MultipartFile file) throws IOException {
        String msg = "";
        if(!file.getOriginalFilename().contains(".xlsx") && !file.getOriginalFilename().contains(".xls")) {
            return "文件格式不对";
        }
        EasyExcel.read(file.getInputStream(), InspectionIqcDto.class, new ReadListener<InspectionIqcDto>(){
            public static final int BATCH_COUNT = 1000;

            private List<InspectionIqcDto> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

            @Override
            public void invoke(InspectionIqcDto t, AnalysisContext analysisContext) {
                //UNIT如为空，默认取PCS
                if(ObjectUtil.isNull(t.getOrNo())) {
                    t.setOrNo("");
                }
                if(ObjectUtil.isNull(t.getOrItem())) {
                    t.setOrItem("");
                }
                if(ObjectUtil.isNull(t.getItemStatus())) {
                    t.setItemStatus("");
                }
                if(ObjectUtil.isNull(t.getDeliveryOrNo())) {
                    t.setDeliveryOrNo("");
                }
                if(ObjectUtil.isNull(t.getOriOrNo())) {
                    t.setOriOrNo("");
                }
                if(ObjectUtil.isNull(t.getMaterialCode())) {
                    t.setMaterialCode("");
                }
                if(ObjectUtil.isNull(t.getMaterialName())) {
                    t.setMaterialName("");
                }
                if(ObjectUtil.isNull(t.getMaterialSpec())) {
                    t.setMaterialSpec("");
                }
                if(ObjectUtil.isNull(t.getReceiveQty())) {
                    t.setReceiveQty(0);
                }
                if(ObjectUtil.isNull(t.getActualQty())) {
                    t.setActualQty(0);
                }

                if(ObjectUtil.isNull(t.getDeliveryTime())) {
                    t.setDeliveryTime(new Date());
                }
                if(ObjectUtil.isNull(t.getActualDeliveryTime())) {
                    t.setActualDeliveryTime(new Date());
                }

                if(ObjectUtil.isNull(t.getProductBatch())) {
                    t.setProductBatch("");
                }

                if(ObjectUtil.isNull(t.getExpirateTime())) {
                    t.setExpirateTime(new Date());
                }

                if(ObjectUtil.isNull(t.getInspection())) {
                    t.setInspection("");
                }

                if(ObjectUtil.isNull(t.getSupplierCode())) {
                    t.setSupplierCode("");
                }

                if(ObjectUtil.isNull(t.getSupplierName())) {
                    t.setSupplierName("");
                }

                if(ObjectUtil.isNull(t.getUrgentRelease())) {
                    t.setUrgentRelease("");
                }

                if(ObjectUtil.isNull(t.getWarehouseName())) {
                    t.setWarehouseName("");
                }

                if(ObjectUtil.isNull(t.getBatchNo())) {
                    t.setBatchNo("");
                }
//                if(ObjectUtil.isNull(t.getMaturingTime())) {
//                    t.setMaturingTime(0);
//                }
//                    t.setUnit("PCS");
////
//                //是否采集SN如为空，默认采集
//                if(ObjectUtil.isNull(t.getGetSn()))
//                    t.setGetSn(true);
//                //是否采集备注如为空，默认不采集
//                if(ObjectUtil.isNull(t.getGetComments()))
//                    t.setGetComments(false);
//                //Warehouse后台可默认写C01
//                if(ObjectUtil.isNull(t.getWarehouse())||  StringUtils.isEmpty(t.getWarehouse()))
//                    t.setWarehouse(DEFAULT_WAREHOUSE);
//                //Plant字段如为空，默认1001
//                if(ObjectUtil.isNull(t.getPlant())||  StringUtils.isEmpty(t.getPlant()))
//                    t.setPlant(DEFAULT_PLANT);
//                //长宽高不为空，自动计算体积，录入后台
//                if(!ObjectUtil.isNull(t.getLength())&& !ObjectUtil.isNull(t.getWidth()) && !ObjectUtil.isNull(t.getHeight()))
//                    t.setVolume(t.getLength()*t.getWidth()*t.getHeight().doubleValue());
//                //如ProductType/ProductFamily为空，根据t_product_type前缀与ProductType/ProductFamily绑定规则，匹配对应的ProductType/ProductFamily值
//                //todo:规则校验
//
//                for(ProductType productType:productTypeList)
//                {
//                    if(t.getMlfb().contains(productType.getMlfbPrefix()))
//                    {
//                        t.setProductType(productType.getProductType());
//                        t.setProductFamily(productType.getProductFamily());
//                        if(productType.getProductType().equals(LICENSE)) {
//                            t.setGetComments(true);
//                        }
//                        break;
//                    }
//                }

                cachedDataList.add(t);
                if (cachedDataList.size() >= BATCH_COUNT) {
                    // 这个是保存数据saveData();
                    // 存储完成清理 list
                    saveData();
                    cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
                }
            }
            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                saveData();
            }

            @Transactional
            private void saveData() {
                //todo: 如果pn重复
                String userName = SecurityUtils.getUsername();
                Map<String, List<InspectionIqcDto>> binMap = cachedDataList.stream().collect(Collectors.groupingBy(task -> task.getOrNo()));
                List<InspectionTaskDto> inspectionTaskDtos = new ArrayList<>();
                for (Map.Entry<String, List<InspectionIqcDto>> entry : binMap.entrySet()) {
                    List<InspectionIqcDto> inspectionIqcDtos = entry.getValue();
                    InspectionTaskDto inspectionTaskDto =new InspectionTaskDto();
                    inspectionTaskDto.setMaterialCode(inspectionIqcDtos.get(0).getMaterialCode());
                    inspectionTaskDto.setOrNo(entry.getKey());
                    inspectionTaskDto.setQty(inspectionIqcDtos.size());
                    inspectionTaskDtos.add(inspectionTaskDto);
                }
                inspectionTaskService.addInspectionTasks(inspectionTaskDtos);



                for(InspectionIqcDto inspectionIqcDto: cachedDataList) {
//                    Material material = new Material();
//                    String materialCode = materialExcelDto.getCode();
//                    Optional<MaterialType> optionalMaterialType = materialTypes.stream().filter(item -> materialCode.startsWith(item.getCode())).findFirst();
//                    if(optionalMaterialType.isPresent()) {
//                        MaterialType materialType = optionalMaterialType.get();
//                        material.setMaterialTypeId(materialType.getId());
//                    }
                    InspectionIqc inspectionIqc = new InspectionIqc();
                    BeanUtils.copyProperties(inspectionIqcDto, inspectionIqc, new String[]{"id"});
                    inspectionIqc.setCreateTime(new Date());
                    inspectionIqc.setCreateBy(userName);
                    inspectionIqc.setDelFlag(false);
                    //
                    inspectionIqcMapper.insert(inspectionIqc);
                }

//                List<Material> exitMats = materialRepository.findMaterialsByPnInAndDelete(pns, 0);
//                List<String> existPns = exitMats.stream().map(item -> item.getPn()).distinct().collect(Collectors.toList());
//                List<Material> materials = cachedDataList.stream().filter(item -> !existPns.contains(item.getPn()))
//                        .map(materialMapper::toEntity).collect(Collectors.toList());
//                materialRepository.saveAll(materials);
            }
        }).sheet(0).headRowNumber(1).doRead();
        return msg;
    }
}




